package basic.study.wantOffer.chapter3;

import java.util.Stack;

/**
 * @ClassName Problem
 * @Description 包含min函数的栈
 * @Company inspur
 * @Author Kevin
 * @Date 2020/5/19 10:35
 * @Version 1.0
 */
public class Problem30 {
    class MinStack {
        Stack<Integer> stack;
        Stack<Integer> helper;

        public MinStack() {
            stack = new Stack<Integer>();
            helper = new Stack<Integer>();
        }

        public void push(Integer x) {
            stack.push(x);

            if (helper.isEmpty() || x <= helper.peek()) {
                helper.push(x);
            }
        }

        public Integer pop() throws Exception {
            if (!stack.isEmpty()) {
                Integer temp = stack.pop();
                if (helper.peek() == temp) {
                    helper.pop();
                }
                return temp;
            } else {
                throw new Exception("Empty Stack cann't Pop!");
            }
        }

        public Integer min() throws Exception {
            if (!helper.isEmpty()) {
                return helper.peek();
            } else {
                throw new Exception("Empty Stack cann't Min!");
            }
        }
    }
}
